package com.samp.solr;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.nio.file.Path;
import java.nio.file.Paths;

public class SampIndexSearcher {
    public void indexSearch(){
        String dirPath = "D:\\solr\\data\\index";
        Path path = Paths.get(dirPath);
        try {
            Directory directory = FSDirectory.open(path);
            IndexReader ir = DirectoryReader.open(directory);
            System.out.println(ir.maxDoc());
            IndexSearcher is = new IndexSearcher(ir);;
            Analyzer analyzer = new SimpleAnalyzer();
            QueryParser queryParser = new QueryParser("description",analyzer);
            Query query = queryParser.parse("中国");
            TopDocs topDocs = is.search(query,10);
            System.out.println(topDocs.totalHits);
            ScoreDoc[] scoreDocs = topDocs.scoreDocs;
            for( ScoreDoc scoreDoc : scoreDocs ){
                Document document =  is.doc(scoreDoc.doc);
                System.out.println(document.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SampIndexSearcher sampIndexSearcher = new SampIndexSearcher();
        sampIndexSearcher.indexSearch();
    }
}
